import { RouteRecordRaw } from "vue-router"
import router from "@/router"
let firstMenu: any = null
// store 处理
export function menuRouter(userMenus: any[] = []): RouteRecordRaw[] {
  const routes: RouteRecordRaw[] = []
  const allRoutes: RouteRecordRaw[] = []
  const routerFile = require.context('../router/main', true, /\.ts/)
  routerFile.keys().forEach(filePath => {
    const path = require('../router/main' + filePath.split('.')[1]).default
    allRoutes.push(path)
  })

  function recurse(userMenus: any[] = []) {
    if (userMenus)

      for (const userMenu of userMenus) {
        // 二级路由
        if (userMenu.menu_type === 1) {
          // 路径匹配成功
          const route = allRoutes.find(item => item.path === userMenu.path)
          if (route) {
            routes.push(route)
          }
          if (!firstMenu) {
            firstMenu = userMenu
          }
        } else {
          // 一级路由
          recurse(userMenu.children ?? [])
        }
      }

  }
  recurse(userMenus)

  return routes
}
// 合并本地静态路由
export function staticRouter() {
  const staticRouters: any[] = [{
    id: 1,
    menu_name: "系统总览",
    parent_pid: 0,
    icon: 'el-icon-monitor',
    path: '/main',
    menu_type: 0,
    children: []
  }]
  router.getRoutes().forEach((route, index) => {
    if (route.path.includes('/main') && route.path != '/main' && !route.path.includes('system')) {
      staticRouters[0].children.push({
        id: 1000 + index,
        menu_name: route.meta.title,
        parent_pid: 1,
        path: route.path,
        component: () => import(`@/views/${route.path}/dashboard.vue`),
        menu_type: 1,
      })
    }
  });
  return staticRouters
}

// menActive处理
export function pathToMenuITemActive(currentPath: string, userMenus: any[]): any {

  for (const menu of userMenus) {
    if (menu.menu_type == 0) {
      const findMenu = pathToMenuITemActive(currentPath, menu.children ?? [])
      if (findMenu) {
        return findMenu
      }
    } else if (menu.menu_type == 1 && menu.path == currentPath) {
      return menu
    }
  }

}


// 权限按钮处理  获取权限按钮
export function menuToPermission(userMenus: any[] = []) {
  let permission: number[] = []

  function recurveGetPermission(userMenus: any[]) {

    for (const menu of userMenus) {

      if (menu.menu_type === 0 || menu.menu_type === 1) {
        recurveGetPermission(menu.children ?? [])
      } else {
        permission.push(menu.perms)
      }

    }
  }
  recurveGetPermission(userMenus)


  return permission
}

export { firstMenu }

// 将菜单 转成树形结构
export function menuToTree(RoleMenus: any[] = []) {
  // 排序确保是父级菜单在前
  RoleMenus.sort((a: any, b: any) => {
    return a.parent_pid - b.parent_pid
  })
  let data: any = []
  let map: any = {}
  RoleMenus.forEach((item: any) => {
    item.children = []
    map[item.id] = item
    if (item.parent_pid == 0) {
      data.push(item)
    } else {
      map[item.parent_pid].children.push(item)
    }
  })
  return data
}


// 分配权限获取叶子节点
export function menuToLeafNodes(RoleMenus: any[] = []) {
  let menuToTreeData = menuToTree(RoleMenus)
  // console.log(menuToTreeData);

  let res: any[] = []
  let recurve = (menuToTreeData: any[]) => {
    menuToTreeData.forEach(item => {
      if (item.children && item.children.length) {
        recurve(item.children)
      } else {
        res.push(item.id)
      }
    })
  }
  recurve(menuToTreeData)
  // console.log(res);

  return res
}

// 路由重置
export function resetRouter(userMenus: any) {
  function recurse(userMenus: any[] = []) {
    if (userMenus)
      for (const userMenu of userMenus) {
        // 二级路由
        if (userMenu.menu_type === 1) {

          if (userMenu.component && userMenu.component != '') {
            if (router.hasRoute(userMenu.component)) {
              router.removeRoute(userMenu.component)
            }
          }

        } else {
          // 一级路由
          recurse(userMenu.children ?? [])
        }
      }
  }
  recurse(userMenus)
}


// 菜单参数过滤

export function separateType(bodyObjs: any) {
  const menu_type = bodyObjs?.menu_type
  //不用类型的菜单过滤字段不同
  let filters: string[] = []
  if (menu_type == 2) {
    // 按钮创建规则匹配
    filters = ['path', 'icon', 'is_cache', 'component']
  } else if (menu_type == 1) {
    // 子菜单创建创建规则匹配
    filters = ['icon', 'perms']
  } else if (menu_type == 0) {
    // 创建菜单规则匹配
    filters = ['path', 'perms', 'is_cache', 'component']
  }
  bodyObjs = filterProperty(filters, bodyObjs)
  return bodyObjs
}
/**
 * 工具函数 过滤不要的字段
 * @param {*} properties
 * @param {*} obj
 * @returns
 */
export function filterProperty(properties: any[], obj: any) {
  Object.keys(obj).forEach((key) => {
    if (properties.includes(key)) {
      delete obj[key]
    }
  })
  return obj
}

/**
 * 创建菜单默认只展开一级菜单
 * @param manes
 * @returns
 */
export function getMenuAndSubMenu(manes: any) {
  let res: any[] = []
  let recurve = (manes: any[]) => {
    manes.forEach(item => {
      if (item.menu_type == 0) {
        res.push(item.id)
      }
      if (item.children && item.children.length) {
        recurve(item.children)
      }
    })
  }
  recurve(manes)
  return res
}


/**
 * 读取所欲的icons下的 svg图标名称 用于菜单图标的显示
 */

export function getIconsSVGName() {
  let iconsSVGNames: any = []
  const routerFile = require.context('../icons/svg', true, /\.svg/)
  routerFile.keys().forEach(filePath => {
    const path = filePath.split('.')[1].replace('/', '')
    iconsSVGNames.push({ value: path })
  })
  return iconsSVGNames
}
